package cn.ai.shoes.core.aop;

import cn.ai.shoes.core.annotation.OpLog;
import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

import static cn.ai.shoes.common.constant.GolbalConstants.OpTypeConstants.OP_UPDATE;


/**
 * 操作日志切面
 */
@Aspect
@Component
@Slf4j
public class OpLogAspect {
    /**
     * 初始化
     */
    @Pointcut("@annotation(cn.ai.shoes.core.annotation.OpLog)")
    public void opLogAspectMethod() {
    }

    /**
     * 在方法之前执行
     */
    @Before("opLogAspectMethod()")
    public void before(JoinPoint joinPoint) throws Throwable{
        log.info("操作日志切面执行");
        //获取方法签名
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        //获取方法
        OpLog annotation = methodSignature.getMethod().getAnnotation(OpLog.class);
        //获取注解
        String opType = annotation.value();
        //判断opType是insert还是update
        if (opType.isBlank()) {
            log.info("----------------------操作类型为空--------------------------");
            return;
        }
        if (opType.equals(OP_UPDATE)) {
            log.info("-------------------操作类型：更新---------------------------");
            Object[] args = joinPoint.getArgs();
            //获取args第一个元素
            Object arg = args[0];
            //给arg设置当前更新时间
            BeanUtil.setFieldValue(arg,"updateTime",LocalDateTime.now());
            //获取创建人
            String name = SecurityContextHolder.getContext().getAuthentication().getName();
            BeanUtil.setFieldValue(arg,"updater",name);
            return;
        }

        log.info("---------------------操作类型：新增---------------------------");
        Object[] args = joinPoint.getArgs();
        //获取args第一个元素
        Object arg = args[0];
        //给arg设置当前时间
        BeanUtil.setFieldValue(arg,"createTime", LocalDateTime.now());
        BeanUtil.setFieldValue(arg,"updateTime",LocalDateTime.now());
        //获取创建人
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        BeanUtil.setFieldValue(arg,"creator",name);
        BeanUtil.setFieldValue(arg,"updater",name);
    }

}
